package com.cx330;

import lombok.Getter;

public class Example91_01 {
    public static void main(String[] args) {
        RealAdminServiceOne01 one = new RealAdminServiceOne01(); // 被代理对象
        AdminServiceOne01 proxyOne = new AdminServiceProxyOne01(one); // 代理类对象
        proxyOne.adminOperationOne();

        RealAdminServiceTwo01 two = new RealAdminServiceTwo01(); // 被代理对象
        AdminServiceTwo01 proxyTwo = new AdminServiceProxyTwo01(two); // 代理类对象
        proxyTwo.adminOperationTwo();
    }
}

interface AdminServiceOne01 { // 主题接口1
    void adminOperationOne();
}

class AdminServiceProxyOne01 implements AdminServiceOne01 { // 代理类1
    private final AdminServiceOne01 target;

    public AdminServiceProxyOne01(AdminServiceOne01 target) {
        this.target = target;
    }

    @Override
    public void adminOperationOne() {
        // 前置处理
        System.out.println("前置处理操作（例如：事务开启）");
        // 权限校验，执行被代理类的方法
        String user = Session01.getUser();
        if ("admin".equals(user)) {
            System.out.println(user + "请求的操作被允许！");
            target.adminOperationOne();
        } else {
            System.out.println(user = "请求的操作被拒绝");
        }
        // 后置处理
        System.out.println("后置处理操作（例如：事务提交）");
    }

}

class AdminServiceProxyTwo01 implements AdminServiceTwo01 { // 代理类2
    private final AdminServiceTwo01 target;

    public AdminServiceProxyTwo01(AdminServiceTwo01 target) {
        this.target = target;
    }

    @Override
    public void adminOperationTwo() {
        // 前置处理
        System.out.println("前置处理操作（例如：事务开启）");
        // 权限校验，执行被代理类的方法
        String user = Session01.getUser();
        if ("admin".equals(user)) {
            System.out.println(user + "请求的操作被允许！");
            target.adminOperationTwo();
        } else {
            System.out.println(user = "请求的操作被拒绝");
        }
        // 后置处理
        System.out.println("后置处理操作（例如：事务提交）");
    }
}

interface AdminServiceTwo01 { // 主题接口2
    void adminOperationTwo();
}

class RealAdminServiceOne01 implements AdminServiceOne01 { // 被代理类1
    @Override
    public void adminOperationOne() {
        System.out.println("执行具体业务操作1");
    }
}

class RealAdminServiceTwo01 implements AdminServiceTwo01 { // 被代理类2
    @Override
    public void adminOperationTwo() {
        System.out.println("执行具体业务操作2");
    }
}

class Session01 {
    @Getter
    public static String user = "admin";
}